using System.Collections;
using DMS.DAOs.NH.ConfOrm;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using ObjectFactories;

namespace BuildTablesAndData
{
	public class Builder
	{
		public void Build()
		{
			#region reset factories

			AlbumFactory.Reset();
			ArtistFactory.Reset();
			CustomerFactory.Reset();
			EmployeeFactory.Reset();
			GenreFactory.Reset();
			InvoiceFactory.Reset();
			MediaTypeFactory.Reset();
			PlaylistFactory.Reset();
			TrackFactory.Reset();

			#endregion

			#region build schema

			Configuration cfg = Config.GetConfiguration();

			SchemaExport se = new SchemaExport(cfg);
			se.Create(false, true);

			#endregion

			#region persist objects

			ISessionFactory sessionFactory = cfg.BuildSessionFactory();

			using (ISession session = sessionFactory.OpenSession())
			using (ITransaction transaction = session.BeginTransaction())
			{
				SaveAll(session, AlbumFactory.GetAll());
				SaveAll(session, ArtistFactory.GetAll());
				SaveAll(session, CustomerFactory.GetAll());
				SaveAll(session, EmployeeFactory.GetAll());
				SaveAll(session, GenreFactory.GetAll());
				SaveAll(session, InvoiceFactory.GetAll());
				SaveAll(session, MediaTypeFactory.GetAll());
				SaveAll(session, PlaylistFactory.GetAll());

				transaction.Commit();
			}

			sessionFactory.Close();

			#endregion
		}

		private static void SaveAll(ISession session, IEnumerable entities)
		{
			foreach (var e in entities)
				if (e != null)
					session.Save(e);
		}

		public void Drop()
		{
			Configuration cfg = Config.GetConfiguration();

			SchemaExport se = new SchemaExport(cfg);
			se.Drop(false, true);

			AlbumFactory.Reset();
			ArtistFactory.Reset();
			CustomerFactory.Reset();
			EmployeeFactory.Reset();
			GenreFactory.Reset();
			InvoiceFactory.Reset();
			MediaTypeFactory.Reset();
			PlaylistFactory.Reset();
			TrackFactory.Reset();
		}
	}
}